package com.yuan.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuan.reggie.common.R;
import com.yuan.reggie.pojo.User;
import com.yuan.reggie.service.UserService;
import com.yuan.reggie.utils.SMSUtils;
import com.yuan.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author yuanxingke
 * @date 2022/8/2 18:39
 */
@RestController
@Slf4j
@RequestMapping("user")
public class UserController {


    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        String phone = user.getPhone();
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        log.info("code:" + code);
        SMSUtils.sendSms(phone, code);
        //保存到session中去
//        session.setAttribute("code", code);

        //将验证码保存到redis中 并且设置有效时间
        redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);

        return R.success("手机验证码短信发送成功");
    }

    @PostMapping("login")
    public R<User> login(@RequestBody Map<String, String> map, HttpSession session) {
        //获取数据
        String phone = map.get("phone");
        String code1 = map.get("code");

        //从session中获取验证码
//        String code2 = (String) session.getAttribute("code");

        //从redis中获取验证码
        String code2 = (String) redisTemplate.opsForValue().get(phone);


        if (!StringUtils.equals(code1, code2)) {
            return R.error("验证码错误");
        }

        //判断手机号码是否为新用户，如果为新用户则注册
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getPhone, phone);
        User user = userService.getOne(lambdaQueryWrapper);
        //如果为空就注册
        if (user == null) {
            user = new User();
            user.setStatus(1);
            user.setPhone(phone);
            //完成注册 保存
            userService.save(user);
        }
        session.setAttribute("user", user.getId());

        //登陆成功 删除验证码
        redisTemplate.delete(phone);
        return R.success(user);
    }


    @PostMapping("loginout")
    public R<String> loginout(HttpSession session){
        session.invalidate();
        return R.success("退出成功");
    }
}
